package com.linln.wxapi;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.ad.domain.AdInfo;
import com.linln.modules.ad.domain.AdTop;
import com.linln.modules.ad.service.AdInfoService;
import com.linln.modules.ad.service.AdTopService;
import com.linln.modules.member.domain.AreaCount;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.AreaCountService;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 轮播图相关小程序接口
 * @author hct
 *
 */
@Api(value="轮播图信息管理")
@RestController
@RequestMapping("/wx/ad/{area}")
public class WxApiAdController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AdInfoService adInfoService;
    @Autowired
    private AdTopService adTopService;
    @Autowired
	  private AreaCountService areaCountService;

	  @Autowired
	  private MemberAgentService memberagentService;
	
	  @Autowired
	  private MemberInfoService memberInfoService;
    /**
     * 获取商户轮播图信息
     * @param area 区域
     * @param typeid（1代表首页轮播图，2代表商户轮播图，3首页菜单，4商户菜单）
     * @return
     */
     @ApiOperation(value = "获取轮播图信息",  notes = "获取轮播图信息")
     @ApiImplicitParams({
          @ApiImplicitParam(name = "typeid", value = "类型 ：1代表首页轮播图，2代表商户轮播图，3首页菜单，4商户菜单",paramType = "query", required = true, dataType = "int")
     })
     @RequestMapping(value = "list",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo adlist(@PathVariable String area, Integer typeid) {
        
         try {
         	 List<AdInfo> list =adInfoService.queryListByTypeAndArea(typeid,area);
             if(list==null || list.size()==0) {
            	 list =adInfoService.queryListByType(typeid);
             }         
             return ResultVoUtil.success(list);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
    
     
     /**
      * 发布消息
      * @param area 区域
      * @param lng  经度
      * @param lat  纬度
      * @return
      */
     @ApiOperation(value = "申请发布广告",  notes = "申请发布广告")
     @RequestMapping(value = "fabu",method= RequestMethod.POST)
     @ResponseBody
     public ResultVo messagefabu(@PathVariable String area,Long memberId,AdInfo ad) {
        
         try {
        	ad.setAdStatus(0); 
        	ad.setAgentId(0L);
        	ad.setNum(0);
        	ad.setReadnum(0);
        	ad.setPayStatus(0);
        	ad.setOrderId(ToolUtil.getRandomString(32));
        	MemberInfo member=new MemberInfo();
        	member.setId(memberId); 
        	ad.setMember(member); 
        	if(ad.getStartTime()!=null)
         	ad.setEndTime(DateUtils.getDateInfo(ad.getStartTime(),ad.getDay()));
          	ad = adInfoService.saveAndSendNotice(ad);
             return ResultVoUtil.success(ad);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
  
     }
     
   /*  
     *//**
      * 获取信息详情
      * @param area 区域
      * @param lng  经度
      * @param lat  纬度
      * @return
      *//*
     @ApiOperation(value = "获取广告详情",  notes = "获取广告详情信息")
     @RequestMapping(value = "detail",method= {RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo messagedetail(@PathVariable String area,Long id) {
        
         try {
         	AdInfo adinfo = adInfoService.getById(id);
         	//baseinfo.setReadnum(baseinfo.getReadnum()+1);
         	//统计访问量         	
         	return ResultVoUtil.success(adinfo);
         } catch (Exception e) {
         	 this.logger.error(e.getMessage(), e);
              return ResultVoUtil.error("接口异常"); 
         }
  
     }
     
     */
     
     
     /**
      * 发布消息
      * @param area 区域
      * @param lng  经度
      * @param lat  纬度
      * @return
      */
     @ApiOperation(value = "编辑发布广告",  notes = "申请发布广告")
     @RequestMapping(value = "edit",method= RequestMethod.POST)
     @ResponseBody
     public ResultVo adedit(@PathVariable String area,Long memberId,AdInfo ad) {
    	 Gson gson=new Gson();
    	 String adString=gson.toJson(ad);
      	System.out.println(DateUtils.format(new Date())+">>>WxApiAdController>>>>adedit======= area>>"+area+">>>ad=="+adString);

         try {
        	 AdInfo adInfoold=adInfoService.getById(ad.getId());
        		MemberInfo memberold=memberInfoService.getById(memberId);
        	     if(memberold!=null &&memberold.getIsagent()!=null && memberold.getIsagent().intValue()==1) {
        	    	adInfoold.setDetailimg(ad.getDetailimg());
					 if(ad.getDay().intValue() > 0){
						 if(StringUtils.isNotEmpty(ad.getOrderCode())){
							 adInfoold.setOrderId(ad.getOrderCode());
							 adInfoold.setDay(ad.getDay());
							 BigDecimal b1 = new BigDecimal(adInfoold.getFee());
							 BigDecimal b2 = new BigDecimal(ad.getFee());
							 Double addFee = b1.add(b2).doubleValue();
							 adInfoold.setFee(addFee);
							 adInfoold.setStartTime(ad.getStartTime());
							 Date now=new Date();
							 if(adInfoold.getEndTime().before(now)) {
								 adInfoold.setEndTime(DateUtils.getDateInfo(now, adInfoold.getDay()));

							 }else {
								adInfoold.setEndTime(DateUtils.getDateInfo(adInfoold.getEndTime(), adInfoold.getDay()));

							 }
						 }
					 }
		        	adInfoold.setImg(ad.getImg());
        	     }
        	adInfoold.setDetails(ad.getDetails());
            ad = adInfoService.save(adInfoold);
       	    
             return ResultVoUtil.success(ad);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
  
     }
     
     
     /**
	     * 获取置顶信息
	* @param area 区域
	
	* @return
	*/
	@ApiOperation(value = "获取信息设置信息",  notes = "获取信息设置信息")
	@RequestMapping(value = "adtop",method= {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public ResultVo messagetop(@PathVariable String area ) {
	
	try {
		// 创建匹配器，进行动态查询匹配
     ExampleMatcher matcher = ExampleMatcher.matching()
             .withMatcher("title", match -> match.contains());
     AdTop baseinfo=new AdTop();
     // 获取数据列表
     Example<AdTop> example = Example.of(baseinfo, matcher);
 
	    List<AdTop> list=adTopService.getList(example);
	    return ResultVoUtil.success(list);
	
	} catch (Exception e) {
	this.logger.error(e.getMessage(), e);
		 return ResultVoUtil.error("失败");
	
	}
	
	}
	
	
	 /**
     * 获取信息详情
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "获取消息详情",  notes = "获取消息详情信息")
    @RequestMapping(value = "detail",method= {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResultVo adDetail(@PathVariable String area,Long id) {
       
        try {
        	AdInfo baseinfo = adInfoService.getById(id);
        	if(baseinfo!=null) {
        		if(baseinfo.getReadnum()==null) {
        			baseinfo.setReadnum(1);
        		}else {
            		baseinfo.setReadnum(baseinfo.getReadnum()+1);        			
        		}
        		adInfoService.updateIsReadAddById(id);
            	//统计访问量
            	AreaCount count=areaCountService.findByArea(area);
            	if(count==null) {
            		count=new AreaCount();
            		count.setArea(area);
            		count.setMessage_readnum(1); 
            		areaCountService.save(count);
            	}else {
            	 areaCountService.updateReadNumByArea(area);
            	}
        	}else {
                return ResultVoUtil.error("信息不存在"); 

        	}        	
        	return ResultVoUtil.success(baseinfo);
        } catch (Exception e) {
        	 this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
        }
 
    }
    
    /**
     * 获取我的置顶信息(置顶部分内容)
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "获取发布的广告信息",  notes = "获取我发布的广告列表信息")
    @RequestMapping(value = "mytoplist",method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResultVo mytoplist(@PathVariable String area,Long memberId,String keyword,
    		 @RequestParam(value = "pageNumber", required = false,defaultValue="1") Integer pageNumber,
  			 @RequestParam(value = "pageSize", required = false,defaultValue="20") Integer pageSize
    		
    		) {
    	
    	System.out.println(DateUtils.format(new Date())+"mytoplist area>>"+area+">>>memberId=="+memberId);

        try {
        	// 创建匹配器，进行动态查询匹配
       	 //满足当前时间置顶的信息
        	// 创建匹配器，进行动态查询匹配
			ExampleMatcher matcher = ExampleMatcher.matching()
					.withMatcher("details", match -> match.contains());
			AdInfo baseinfo=new AdInfo();
 			baseinfo.setAdStatus(1);
 			baseinfo.setPayStatus(1);
 			if(keyword!=null && !"".equals(keyword)){
				baseinfo.setDetails(keyword);				
			} 
            Map<String,Object> map=new HashMap<String,Object>();  
       	    Example<AdInfo> examplenone =null;
       	    
       	 MemberAgent memberAgent= memberagentService.getByMemberIdAndArea(memberId, area);
         Page<AdInfo> list =null;
         if(memberAgent!=null) {
         	 baseinfo.setArea(area);
         	 examplenone = Example.of(baseinfo, matcher);
             list = adInfoService.getPageList(examplenone, pageNumber,pageSize);
         	
         }else {
         
        	MemberInfo memberInfo=new MemberInfo();
  			memberInfo.setId(memberId);
  			baseinfo.setMember(memberInfo);
 			examplenone = Example.of(baseinfo, matcher);       	    
			list = adInfoService.getPageList(examplenone, pageNumber,pageSize);
           
         }
         map.put("list", list.getContent());
         map.put("pageNumber", list.getPageable().getPageNumber()+1);
         map.put("pageSize", list.getPageable().getPageSize());
         map.put("pageCount", list.getTotalPages());
         map.put("allCount", list.getTotalElements());
         return ResultVoUtil.success(map);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常》》》"+this.getClass().getName()); 

        }
 
    }
   
}
